let http = require("http");

function myHttp(param, url) {
    let options = {
        hostname: 'support.lenovo.com.cn',
        port: 80,
        method: 'POST',
        headers: {
            "Connection": "keep-alive",
            "Referer": 'support.lenovo.com.cn',
            "Content-Type": "application/x-www-form-urlencoded",
            "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"
        } //伪造请求头
    };
    if (!url) {
        options.path = '/lenovo/wsi/handlers/GetBaoxiuPeizhi.ashx'
    } else {
        options.path = url
    }
    //封装成promise，方便调用
    let promise = new Promise(function (resolve, rejecte) {
        let req = http.request(options, function (res) {
            let bodyChunks = [];
            res.on('data', function (chunk) {
                    bodyChunks.push(chunk);
                })
                .on('end', function () {
                    let body = Buffer.concat(bodyChunks);
                    resolve(body.toString())
                });
        })
        //传递请求参数
        req.write(params(param))
        //结束请求，不结束服务器不返回数据
        req.end()
    })

    return promise;
}
//工具方法json转querystring
function cleanArray(actual) {
    const newArray = []
    for (let i = 0; i < actual.length; i++) {
        if (actual[i]) {
            newArray.push(actual[i])
        }
    }
    return newArray
}
//同上
function params(json) {
    if (!json) return ''
    return cleanArray(Object.keys(json).map(key => {
        if (json[key] === undefined) return ''
        return encodeURIComponent(key) + '=' +
            encodeURIComponent(json[key])
    })).join('&')
}
//编码转换方法
function decodeUnicode(str) {
    str = str.replace(/\\/g, "%");
    return unescape(str);
}

module.exports = {
    myHttp,
    decodeUnicode
}
